package com.educate.book.rpc.provide.service;

import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.book.dao.BookDao;
import com.educate.book.model.bo.BookBO;
import com.educate.book.model.po.Book;
import com.educate.book.rpc.api.BookService;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.common.web.IdGen;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Service(version = "${api.service.version}", application = "${dubbo.application.id}", protocol = "${dubbo.protocol.id}", registry = "${dubbo.registry.id}")
public class BookServiceImpl implements BookService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	BookDao bookDao;

	@Override
	public String create(BookBO bo) {
		bo.setBookId(IdGen.uuid());
		// 查询是否有相同的
//		Page<BookBO> page = this.query(bo);
//		if (null != page) {
//			if (page.getSize() > 0) {
//				logger.info("已经有相同的书：" + bo.toString());
//				return "-1";
//			}
//		}
		bookDao.insert(bo);
		return bo.getBookId();

	}

	@Override
	public void delete(BookBO bo) {
		bookDao.delete(bo);
	}

	@Override
	public void delete(String bookId) {
		bookDao.deleteById(bookId);
	}

	@Override
	public BookBO detail(String bookId) {
		Optional<Book> optional = bookDao.findById(bookId);
		if (!optional.isPresent()) {
			throw new AppException("不存在的实例");
		}
		return new BookBO(optional.get());
	}

	@Override
	public BookBO detail(BookBO bo) {
		return detail(bo.getBookId());
	}

	@Override
	public void update(BookBO bo) {
		Optional<Book> optional = bookDao.findById(bo.getBookId());
		if (!optional.isPresent()) {
			throw new AppException("不存在的实例");
		}
		BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
		bookDao.save(optional.get());
	}

	@Override
	public Page<BookBO> query(BookBO bo) {
		return bookDao.query(bo, bo.pageable()).map(BookBO::new);
	}

	@Override
	public List<BookBO> list(BookBO bo) {
		List<Book> result = bookDao.findAll();
		return ListUtils.map(result, BookBO::new);
	}

}
